import mongoose from 'mongoose'
const { ErrorHandler } = require('./common/errorHandler')
const { LocalRequestAllowed } = require('./common/localRequestAllowed')
import utils from '../utils'
import config from '../config'
const jwt = require('jsonwebtoken')
const Users = mongoose.model('Users')
const SMS = mongoose.model('SMS')
mongoose.set('useFindAndModify', false)

export const userStorage = async (ctx) => { 
  try {
    await LocalRequestAllowed(ctx).then(async () => { // 只允许本地请求
      let {
        avatarUrl,
        city,
        country,
        gender,
        language,
        nickName,
        province,
      } = ctx.request.body
      let dataTemp = await Users.findOne({ nickName }).exec()
      if(!dataTemp) {
        const token = jwt.sign({ nickName }, config.passCode)
        await Users.create({ nickName, avatarUrl, province, city, country, gender, language, token: '', registerIP: ctx.ip , lastLoginIP: '', lastAcitveTime: new Date()  })
        
        ctx.body = {
          success: true,
          info: {
            token,
            nickName
          },
          data: '用户数据保存成功'
        }
      }else {
        const token = jwt.sign({ nickName }, config.passCode)
        await Users.findOneAndUpdate({nickName}, { token, lastLoginIP: ctx.ip, lastLoginTime: new Date(), lastAcitveTime: new Date() }).exec()
        ctx.body = {
          success: true,
          data: '用户数据更新成功',
          info: {
            token,
            nickName
          }
        }
      }
    })
  } catch (e) {
    ErrorHandler(e, ctx)
  }
}

export const register = async (ctx) => { // 用户注册
  try {
    let { userName, passWord, phone, validateCode } = ctx.request.body
    const smsTemp = await SMS.findOne({ phone }, {}, {
      sort: {
        'createTime': -1
      }
    }).exec()
    if (smsTemp === null) {
      ctx.body = {
        success: false,
        data: '验证码无效'
      }
    } else if ((Date.parse(new Date()) - Date.parse(smsTemp.createTime)) / 1000 > (10 * 60)) { // 验证码超过10分钟
      ctx.body = {
        success: false,
        data: '验证码已失效'
      }
    } else if (smsTemp && smsTemp.code !== validateCode) { // 验证码不匹配
      ctx.body = {
        success: false,
        data: '验证码错误'
      }
    } else {
      const dataTemp = await Users.findOne({ userName }).exec() // 查询是否已存在的用户名
      const phoneTemp = await Users.findOne({ phone }).exec() // 查询是否已存在的手机号
      if (dataTemp !== null) {
        ctx.body = {
          success: false,
          data: '用户名已存在'
        }
      } else if (phoneTemp !== null) {
        ctx.body = {
          success: false,
          data: '手机号已存在'
        }
      } else { // 注册操作
        await Users.create({ userName, passWord, phone, token: '', lastLoginIP: '', registerIP: ctx.ip })
        await SMS.findOneAndUpdate({ phone }, { status: 1 }).exec()
        const token = jwt.sign({ userName }, config.passCode)
        ctx.body = {
          success: true,
          info: {
            token,
            userName
          },
          data: '注册成功'
        }
      }
    }
  } catch (e) {
    ErrorHandler(e, ctx)
  }
}

export const ifRegister = async (ctx) => { // 是否注册
  try {
    await LocalRequestAllowed(ctx).then(async () => { // 只允许本地请求
      let { userNameOrPhone } = ctx.request.query
      let dataTempFilter = ''
      let dataType = ''
      await utils.ifPhoneNum(userNameOrPhone).then(async res => {
        dataType = 'phone'
        dataTempFilter = { phone: userNameOrPhone }
      }).catch(async e => {
        dataType = 'userName'
        dataTempFilter = { userName: userNameOrPhone }
      })
      const registerInfo = await Users.findOne(dataTempFilter).exec()
      if (registerInfo !== null && dataType === 'phone') {
        ctx.body = {
          success: false,
          data: '已存在的手机号'
        }
      } else if (registerInfo !== null && dataType === 'userName') {
        ctx.body = {
          success: false,
          data: '已存在的用户名'
        }
      } else {
        ctx.body = {
          success: true,
          data: '未注册'
        }
      }
    })
  } catch (e) {
    ErrorHandler(e, ctx)
  }
}

export const login = async (ctx) => { // 用户登录
  try {
    await LocalRequestAllowed(ctx).then(async () => { // 只允许本地请求
      let { userName, passWord } = ctx.request.body
      let dataTempFilter = ''
      await utils.ifPhoneNum(userName).then(async res => {
        dataTempFilter = { phone: userName }
      }).catch(async e => {
        dataTempFilter = { userName: userName }
      })
      const dataTemp = await Users.findOne(dataTempFilter).exec() // 查询是否已存在的用户名/手机号
      if (dataTemp === null) {
        ctx.body = {
          success: false,
          data: '不存在的用户名/手机号'
        }
      } else {
        if (passWord !== dataTemp.passWord) { // 校验密码
          ctx.body = {
            success: false,
            data: '密码错误'
          }
        } else {
          const token = jwt.sign({ userName: dataTemp.userName }, config.passCode)
          await Users.findOneAndUpdate(dataTempFilter, { token, lastLoginIP: ctx.ip, lastLoginTime: new Date(), lastAcitveTime: new Date() }).exec()
          ctx.body = {
            success: true,
            data: '登录成功',
            info: {
              token,
              userName
            }
          }
        }
      }
    })
  } catch (e) {
    ErrorHandler(e, ctx)
  }
}

export const getValidateCode = async (ctx) => { // 获取验证码
  try {
    await LocalRequestAllowed(ctx).then(async () => { // 只允许本地请求
      let { phone } = ctx.request.body
      const ifPhoneNum = await utils.ifPhoneNum(phone)
      if (!ifPhoneNum) {
        ctx.body = {
          success: false,
          data: '无效的手机号'
        }
      } else {
        const dataTemp = await SMS.findOne({ phone: phone }, {}, {sort: {
          'createTime': -1
        }}).exec() // 查询是否已存在
        if (dataTemp && ((new Date().getTime() - dataTemp.createTime) / 1000) < (1 * 60)) { // 如果是在五分钟之内发送的
          ctx.body = {
            success: false,
            data: '验证码发送太频繁'
          }
        } else {
          await SMS.create({
            phone: phone,
            code: utils.mathRandNum(6)
          }) // 创建6位短信验证码
          ctx.body = {
            success: true,
            data: '验证码已发送'
          }
        }
      }
    }).catch(e => {
      ctx.body = {
        success: false,
        data: e.message
      }
    })
  } catch (e) {
    ErrorHandler(e, ctx)
  }
}



